from django.shortcuts import render

# Create your views here.
from redis import StrictRedis
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.utils import jwt_payload_handler, jwt_encode_handler

from libs.sinaweibopy3 import weiboApi

# 生成二维码url
from oauth.models import OauthUser
from user.models import User
from user.utils import validatePassword


# 返回微博登录链接
class Oauth(APIView):
    def post(self, request):
        # 1. 什么都不用接收
        # 2. 生成链接
        wb_url = weiboApi.get_authorize_url()
        # 3. 返回链接
        return Response({'code': 0, 'msg': '获取成功', 'url': wb_url})


class OauthCallBackAPIView(APIView):
    def post(self, request):
        # 1. 接收code
        code = request.data.get('code')
        if code:
            pass
        else:
            return Response({'code': '999', 'msg': 'code无效'})
        # 2. 根据code换取 access_token, wb_uid
        data = weiboApi.request_access_token(code)  # access,  uid
        # 3. 查看wb_uid是否已经绑定
        print(data)
        weibo_uid = data.get('uid')
        try:
            oauth_user = OauthUser.objects.get(uid=weibo_uid)
        except Exception as e:
            oauth_user = None

        if oauth_user:
            pass
            # 4. 如果已经绑定, 那么找到syl用户进行登录(生成token)
            user = oauth_user.user  # 获取用户
            # 为用户生成token
            payload = jwt_payload_handler(user)  # 根据用户,生成 jwt的payload部分内容
            token = jwt_encode_handler(payload)  # 根据payload内容, 生成token
            return Response({'code': '0', 'msg': '登录成功', 'type': '0', 'token': token, 'username': user.username})
        else:
            pass
            # 5. 如果没有绑定, 那么把wb_uid返回给前端, 并且展示绑定界面
            return Response({'code': '0', 'msg': '需要绑定用户', 'type': '1', 'weibo_uid': weibo_uid})
            # type, 1,需要绑定,  0: 不需要绑定
        # 6. 前端携带wb_uid和用户名密码发送到绑定接口


class OauthBind(APIView):
    def post(self, request):
        # 不论是 老用户还是新用户,  都需要输入 邮箱 和 密码
        # 根据bind_type 判断绑定类型, 如果是1. 新用户, 需要校验邮箱验证码,和密码格式
        # 如果是 2. 老用户, 验证密码是否正确.
        # 1. 获取参数,bind_type,  weibo_uid,  email, password,mail_code
        bind_type = request.data.get('bind_type')  #
        if bind_type:
            pass
        else:
            return Response({'code': '999', 'msg': '缺少绑定类型'})

        # 验证一下是否绑定过
        weibo_uid = request.data.get('weibo_uid')
        try:
            OauthUser.objects.get(uid=weibo_uid)
        except Exception as e:
            pass
        else:  # 如果try不出错, 那么执行else中的语句
            return Response({'code': '999', 'msg': '此微博用户已经绑定过了'})

        if bind_type == '1':
            weibo_uid = request.data.get('weibo_uid')
            email = request.data.get('email')
            password = request.data.get('password')
            mail_code = request.data.get('mail_code')
            if all([bind_type, weibo_uid, email, password]):
                pass
            else:
                return Response({'code': '999', 'msg': '参数不全'})
            if bind_type == '1' and mail_code:
                pass
            else:
                return Response({'code': '999', 'msg': '缺少邮箱验证码'})

            # 验证密码格式, 新老用户都验
            if validatePassword(password):
                pass
            else:
                return Response({'code': 999, 'msg': '密码格式错误'})

            # 验证邮箱验证码
            redis_client = StrictRedis()
            redis_email_code = redis_client.get(email)  # 返回来的是None 或者 bytes
            if redis_email_code:
                redis_email_code = redis_email_code.decode()
            if mail_code == redis_email_code:
                pass
            else:
                return Response({'code': 999, 'msg': '邮箱验证码错误'})

            # 2. 先查这个邮箱是否被注册了, 根据username获取用户
            try:
                user = User.objects.get(username=email)
            except Exception as e:
                user = None
            if user:
                # 3. 如果获取到用户, 新用户使用了 已经注册过的邮箱
                return Response({'code': '999', 'msg': '邮箱已注册'})
            else:
                # 4. 如果没有获取到用户, 那么生成一个新用户,
                user = User.objects.create_user(username=email, email=email, password=password)
        else:
            # 老用户绑定
            weibo_uid = request.data.get('weibo_uid')
            email = request.data.get('email')
            password = request.data.get('password')

            if all([weibo_uid, email, password]):
                pass
            else:
                return Response({'code': '999', 'msg': '参数不全'})

            # 2. 根据username获取用户
            try:
                user = User.objects.get(username=email)
            except Exception as e:
                user = None
            if user:
                # 3. 如果获取到用户, 那么判断一下密码是否正确
                if user.check_password(raw_password=password):
                    pass
                else:
                    return Response({'code': '999', 'msg': '密码错误'})
            else:
                # 4. 如果没有获取到用户, 给前端返回用户不存在,
                return Response({'code': '999', 'msg': '用户不存在'})
        # 这里是有一个 user 变量

        # 5. 绑定weibo_uid 和 用户或者新用户,
        OauthUser.objects.create(uid=weibo_uid, user=user)  # user_id=user.id,  user=user, user=user.id
        # 6. 为用户生成token, 进行登录
        payload = jwt_payload_handler(user)  # 根据用户,生成 jwt的payload部分内容
        token = jwt_encode_handler(payload)  # 根据payload内容, 生成token
        return Response({'code': '0', 'msg': '登录成功', 'type': '0', 'token': token, 'email': user.username})

